package org.example.model.manage.bean.po.security;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;

public class SimpleGrantedAuthorityDeserializer extends JsonDeserializer<SimpleGrantedAuthority> {

    @Override
    public SimpleGrantedAuthority deserialize(JsonParser p, DeserializationContext ctxt) 
            throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);
        
        // 如果节点是字符串，直接使用
        if (node.isTextual()) {
            return new SimpleGrantedAuthority(node.asText());
        }
        
        // 如果节点是对象，尝试获取authority字段
        if (node.isObject() && node.has("authority")) {
            return new SimpleGrantedAuthority(node.get("authority").asText());
        }
        
        // 如果节点是对象但没有authority字段，尝试获取第一个字段的值
        if (node.isObject()) {
            String firstFieldName = node.fieldNames().next();
            if (firstFieldName != null) {
                return new SimpleGrantedAuthority(node.get(firstFieldName).asText());
            }
        }
        
        // 默认情况，使用节点的文本值
        return new SimpleGrantedAuthority(node.asText());
    }
}
